import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import HttpApi from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
import enUs from '@/locales/en-US.json';
import zhCn from '@/locales/zh-CN.json';

const borwerlng = window.navigator.language || 'zh-CN';
const borwerlngMap: any = {
    'en': 'en-US',
    'en-US': 'en-US',
    'zh': 'zh-CN',
    'zh-CN': 'zh-CN',
}
const i18nextLng = borwerlngMap[borwerlng] || 'zh-CN'
const i18nInstance = i18n
    .use(HttpApi) // 如果你需要从服务器加载翻译资源
    .use(LanguageDetector) // 如果你需要自动检测用户语言
    .use(initReactI18next) // 将 i18next 传递给 react-i18next
    .init({
        // 引入资源文件
        resources: {
            'en-US': {
                i18n: enUs,
            },
            'zh-CN': {
                i18n: zhCn,
            },
        },
        fallbackLng: i18nextLng, // en-US
        debug: false,
        interpolation: {
            escapeValue: false, // not needed for react as it escapes by default
        },
        detection: {
            // order and from where user language should be detected
            order: ['querystring', 'localStorage'],
            // keys or params to lookup language from
            lookupQuerystring: 'lng',
            lookupCookie: 'i18next',
            lookupLocalStorage: 'i18nextLng',
            lookupFromPathIndex: 0,
            lookupFromSubdomainIndex: 0,
            caches: ['localStorage'],
            excludeCacheFor: ['cimode'],
            htmlTag: document.documentElement,
        },
        ns: ['i18n'],
        defaultNS: 'i18n',
    })

export default i18nInstance
